from views.base import BaseHandler
from db.datab import db
from util.myredis import r
import requests,json

def gettoken():
    #从redis中获取
    key='banktoken'
    rekey='rebanktoken'
    token = r.get_str(key)
    retoken = r.get_str(rekey)
    #redis中不存在说明没有登录过，需要登录
    if not token:
        res = requests.post("http://localhost:5000/login",{'name':'zs','password':'123'})
        user = json.loads(res.text)
        token = user['token']
        retoken = user['retoken']
        r.set_str(key,token)
        r.set_str(rekey,retoken)
        #登录成功返回token
        return token

    #redis中token存在
    #调用checktoken验证是否过期
    mes = requests.get('http://localhost:5000/checktoken',headers={"token":token})
    mm = json.loads(mes.text)
    code = int(mm['code'])
    #已经过期
    if code == 401:
        #通过刷新retoken接口来给token延长时间
        rrtoken = requests.post('http://localhost:5000/retoken',data={"retoken":retoken})
        rtokenmes = json.loads(rrtoken.text)
        #刷新token成功
        if int(rtokenmes['code']) == 200:
            token = rtokenmes['token']
            r.set_str(key,rtokenmes['token'])
            r.set_str(rekey,rtokenmes['retoken'])
        else:
            #刷新token失败，retoken也失效，重新登录
            res = requests.post("http://localhost:5000/login",{'name':'zs','password':'123'})
            user = json.loads(res.text)
            token = user['token']
            retoken = user['retoken']
            r.set_str(key,token)
            r.set_str(rekey,retoken)
           
    return token

class OpenbankHandler(BaseHandler):
    def get(self):
        print("###")
        # #获取到id和状态，更新开户表状态
        # id = self.get_query_argument('id')
        # status = self.get_query_argument('status')
        # #更新数据库
        # sql ="update open_bank set status=%d where id=%d"%(int(status),int(id))
        # db.update(sql)
        self.redirect("http://localhost:8080/#/updateassdfs")
       
    def post(self):
        #从vue页面获取用户输入
        id=1
        code = '234'
        #交易密码
        password = "234"
        name='234'
        bankcode='234'
        #验证
        #写入开户表
        # userid  image_url code username  bank_code  mobile  pay_password  status
        # sql="insert into open_bank(userid,image_url,code)"
        # id = db.update(sql)
        # 调用银行存管理平台开户验证
        token = gettoken()
 
        # print(str(token.decode()))
        redirect_uri = "http://localhost:8000/userbank"
        url = 'http://localhost:5000/open_bank?id=%d&code=%s&name=%s&bankcode=%smobile=%s&token=%s&redirect_uri=%s'%(int(id),code,name,bankcode,bankcode,token,redirect_uri)
        self.finish({"code":200,'url':url})
       
       
